<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>事件委托</title>
    <style>
      .big {
        width: 300px;
        height: 300px;
        background-color: green;
      }
      .center {
        width: 200px;
        height: 200px;
        background-color: blue;
      }
      .small {
        width: 100px;
        height: 100px;
        background-color: pink;
      }
      .inner {
        width: 50px;
        height: 50px;
        background-color: red;
      }
    </style>
  </head>
  <body>
    <div class="big">
      <div class="center">
        <div class="small"></div>
      </div>
    </div>

    <script>
      // DOM事件流：事件捕获，事件冒泡
      // 事件委托：子元素把事情委托给父元素做(e.target能拿到用户操作的元素)
      const div = document.querySelectorAll("div");
      const big = document.querySelector(".big");
      const small = document.querySelector(".small");

      // 事件委托，子元素把事情委托给父元素做
      big.onclick = function (e) {
        console.log("I am", e.target.className);
      };

      // 原本的监听事件，很消耗内存
      /* for (let index = 0; index < div.length; index++) {
          const element = div[index];
          element.onclick = function (){
            console.log('I am',this.className)
          }
      } */

      // 事件委托能为之后新增的DOM元素依然添加事件
      const inner = document.createElement("div");
      inner.className = "inner";
      small.appendChild(inner);
    </script>
  </body>
</html>
